package com.foreknow.dao.impl;

import com.foreknow.dao.GuestBookDao;
import com.foreknow.db.DBManager;
import com.foreknow.db.JdbcTemplate;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.GuestBook;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class GuestBookDaoImpl extends BaseDAO implements GuestBookDao{
    private JdbcTemplate jt;
    private MappingFactory mappingFactory;
    private EntityMapping mapping;

    @Override
    public boolean save(GuestBook gb) throws SQLException {
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        jt = JdbcTemplate.getInstance();
        jt.setConnection(conn);
        int i= jt.update("insert into guestbook(name,phone,email,title,content) values(?,?,?,?,?)",
                gb.getName(),gb.getPhone(),gb.getEmail(),gb.getTitle(),gb.getContent());
        return i==1;
    }

    @Override
    public List<Object> getQueryAll() throws SQLException {
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        jt = JdbcTemplate.getInstance();
        jt.setConnection(conn);
        //需要从工厂类容器map中获取到GuestBookMapping对象
        mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jt.query("select * from guestbook",mapping);
        return list;
    }

    @Override
    public GuestBook getQueryById(int id) throws SQLException {
        //需要从工厂类容器map中获取到GuestBookMapping对象
        mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jt.query("select * from guestbook where id=?", mapping, id);
        if (list.size()>0){
            GuestBook gb = (GuestBook) list.get(0);
            return gb;
        }
        return null;
    }

    @Override
    public boolean deleteById(int id) throws SQLException {
        Connection conn = DBManager.getInstance().getConnection();
        JdbcTemplate jt=JdbcTemplate.getInstance();
        jt.setConnection(conn);
        //String sql = "delete * from guestbook where id=?";
        int isRight = jt.update("delete from guestbook where id=?",id);
        return isRight==1;
    }
}
